package com.scs.application.modules.upms.excel.handler;

import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.scs.application.core.utils.Reflections;
import com.scs.application.core.utils.SpringHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.service.UserService;

import java.util.List;
import java.util.Map;

/**
 */
public class UserDataHandler extends ExcelDataHandlerDefaultImpl {

    private Map<String, User> codeMap = Maps.newHashMap();

    public UserDataHandler() {
        List<User> users = getUserService().list(Wrappers.<User>query().select("id,login_key"));
        for (User user : users) {
            codeMap.put(user.getLoginKey(), user);
        }

    }

    @Override
    public String[] getNeedHandlerFields() {
        return new String[]{"登录账号"};
    }

    @Override
    public Object importHandler(Object obj, String name, Object value) {

        if (!"登录账号".equalsIgnoreCase(name)) {
            return null;
        }
        if (value == null || StringUtils.isBlank(value.toString())) {
            return null;
        }
        User user = codeMap.get(value.toString());
        if (user != null && Reflections.getAccessibleField(obj, "id") != null) {
            Reflections.setFieldValue(obj, "id", user.getId());
        }

        return null;
    }


    public UserService getUserService() {
        return SpringHolder.getBean(UserService.class);
    }

}
